﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LightLog.Entity;
using LightLog.Framework;
using LightLog.IService;

namespace LightLog.Service
{
    public class InitDBService : IInitDBService
    {
        private readonly IFreeSql _fsql;

        public InitDBService(IFreeSql fsql)
        {
            _fsql = fsql;
        }

        public void CreateTable()
        {
            Type myType = typeof(Entity.User);
            var assembly = myType.Assembly; //获取当前父类所在的程序集
            var assemblyAllTypes = assembly.GetTypes(); //获取该程序集中的所有类型
            foreach (var itemType in assemblyAllTypes) //遍历所有类型进行查找
            {
                bool haveTable = _fsql.DbFirst.ExistsTable(itemType.Name);
                if (!haveTable)
                {
                    _fsql.CodeFirst.SyncStructure(itemType);
                }
            }
        }

        public async Task<bool> InitDataAsync()
        {
            bool haveAdmin = await _fsql.Select<Entity.User>().Where(p => p.ID == 1).AnyAsync();
            if (!haveAdmin)
            {
                Entity.User user = new User()
                {
                    ID = 1,
                    IsAdmin = true,
                    Pwd = Security.GetMd5Pwd("123456"),
                    Remark = "管理员不可以删除!",
                    UserName = "Admin",
                };
                return await _fsql.Insert(user).ExecuteAffrowsAsync() > 0;
            }

            return false;
        }
    }
}
